package com.starhub.integration.sdk.custom.model;

import java.io.IOException;
import java.util.List;

import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.model.scoring.ScoringModel;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Configurable;

import com.starhub.integration.sdk.custom.core.CustomRerankerClient;
import com.starhub.integration.sdk.custom.core.CustomRerankerClientConnector;

/**
 * 私有化重排序模型
 * @version: V1.0
 * @author: liuhf
 * @time 2025-08-08
 */
@Builder
@Configurable
public class CustomScoringModel implements ScoringModel {
    
    public static class CustomScoringModelBuilder {
        private String mark;
        private String apiUrl;
        private String modelName;
        
        public CustomScoringModelBuilder mark(String mark) {
            this.mark = mark;
            return this;
        }
        
        public CustomScoringModelBuilder apiUrl(String apiUrl) {
            this.apiUrl = apiUrl;
            return this;
        }
        
        public CustomScoringModelBuilder modelName(String modelName) {
            this.modelName = modelName;
            return this;
        }
        
        public CustomScoringModel build() {
            return new CustomScoringModel(mark, apiUrl, modelName);
        }
    }
    
    private static volatile CustomRerankerClientConnector clientConnector;
    private static final Object lock = new Object();
    
    private CustomRerankerClientConnector getClientConnector() {
        if (clientConnector == null) {
            synchronized (lock) {
                if (clientConnector == null) {
                    clientConnector = new CustomRerankerClientConnector();
                }
            }
        }
        return clientConnector;
    }

    private final String mark;
    private final String apiUrl;
    private final String modelName;
    
    /**
     * 构造函数
     * @param mark 模型标识
     * @param apiUrl API服务地址
     * @param modelName 模型名称
     */
    public CustomScoringModel(String mark, String apiUrl, String modelName) {
        this.mark = mark;
        this.apiUrl = apiUrl;
        this.modelName = modelName;
    }
    
    /**
     * 解析API URL，获取主机地址和路径
     * @return 包含apiHost和apiPath的数组
     */
    private String[] parseApiUrl() {
        if (apiUrl == null || apiUrl.trim().isEmpty()) {
            throw new IllegalArgumentException("私有化重排序模型需要配置API URL");
        }
        
        // 解析API URL格式: http://host:port/path
        String[] urlParts = apiUrl.split("/", 4);
        if (urlParts.length < 4) {
            throw new IllegalArgumentException("API URL格式错误，应为: http://host:port/path");
        }
        
        String apiHost = urlParts[0] + "//" + urlParts[2]; // http://host:port
        String apiPath = "/" + urlParts[3]; // /path
        
        return new String[]{apiHost, apiPath};
    }

    /**
     * 对文本段列表进行重排序评分
     * @param segments 文本段列表
     * @param query 查询文本
     * @return 评分列表
     */
    @Override
    public Response<List<Double>> scoreAll(List<TextSegment> segments, String query) {
        try {
            String[] urlParts = parseApiUrl();
            CustomRerankerClient customRerankerClient = getClientConnector().getCustomRerankerClient(mark, urlParts[0], modelName, urlParts[1]);
            List<Double> scores = customRerankerClient.getRerankerScores(
                segments.stream().map(TextSegment::text).toList(), 
                query
            );
            return Response.from(scores);
        } catch (IOException e) {
            throw new RuntimeException("重排序评分失败: " + e.getMessage(), e);
        }
    }

    public String getMark() {
        return mark;
    }

    public String getApiUrl() {
        return apiUrl;
    }

    public String getModelName() {
        return modelName;
    }
} 